package com.zqsign.core.key.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.KeyStore.PasswordProtection;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import com.zqsign.common.base64.Base64;
import com.zqsign.common.core.secretkey.CertificateDealt;
import com.zqsign.common.utils.StringUtil;

import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateIssuerName;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateValidity;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;

public class CertificateDataUtils {
	private static KeyPairGenerator kpg = null;

	/**
	 * 
	 * 生成keystore和P10。。
	 * 
	 * @param certDn
	 *            certDn证书的标题如：CN=某某,OU=身份证号或企业证件号,O=哪家公司帮某某申请,L=省份,ST=企业城市,C=
	 *            所在国家
	 * @param keyName
	 *            数字证书的别名默认mykey
	 * @return object[0]=P10格式数据 object[1]=数字证书keystore object[2]=数字证书密码
	 * @throws Exception
	 *             生成证书失败
	 */
	public static Object[] getCaP10_3(String certDn, String keyName) throws Exception {
		Object[] obj = new Object[3];
		// 产生8位随机密码
		String passwrod = StringUtil.getRandomString(8);
		X509Certificate cert = null;
		ByteArrayOutputStream keystoreFile = null;
		String signAlgorithm = "SHA1WithRSA"; // 设置证书的加密方式
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
		store.load(null, null);
		kpg = KeyPairGenerator.getInstance("RSA");// 设置证书的加密方式
		kpg.initialize(1024);
		KeyPair keyPair = kpg.generateKeyPair();
		PublicKey pubKey = keyPair.getPublic();
		// 私钥
		PrivateKey priKey = keyPair.getPrivate();
		X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
		X500Principal xp = new X500Principal(certDn);
//		System.out.println("证书标题：" + certDn + "---" + keyName);
		certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
		// 设置颁发者
		certGen.setIssuerDN(xp);
		// 设置使用者
		// 设置有效期
		certGen.setNotBefore(new Date());

		Calendar calendar = Calendar.getInstance();
		Date date = new Date(System.currentTimeMillis());
		calendar.setTime(date);
		calendar.add(Calendar.YEAR, +1);
		certGen.setNotAfter(calendar.getTime());

		certGen.setSubjectDN(xp);
		// 公钥
		certGen.setPublicKey(pubKey);
		certGen.setSignatureAlgorithm(signAlgorithm);
		cert = certGen.generateX509Certificate(keyPair.getPrivate(), "BC");
		// 将证书信息写入到jks中
		store.setKeyEntry(keyName, keyPair.getPrivate(), passwrod.toCharArray(), new Certificate[] { cert });
		PKCS10CertificationRequest p10CertificationRequest = new PKCS10CertificationRequest(signAlgorithm, xp,
				keyPair.getPublic(), null, keyPair.getPrivate());
		// 得到p10格式数据
		String p10 = new String(Base64.encode(p10CertificationRequest.getEncoded()));
		keystoreFile = new ByteArrayOutputStream();
		store.store(keystoreFile, passwrod.toCharArray()); // 获取生成数字证书
		obj[0] = p10;
//		System.out.println("p10===========================================" + p10.toString());
		obj[1] = keystoreFile.toByteArray();
		obj[2] = passwrod;
//		System.out.println("p10===pdw================================" + passwrod.toString());
		if (keystoreFile != null)
			keystoreFile.close();
		return obj;

	}

	/**
	 * 
	 * 生成keystore和P10。。
	 * 
	 * @param certDn
	 *            certDn证书的标题如：CN=某某,OU=身份证号或企业证件号,O=哪家公司帮某某申请,L=省份,ST=企业城市,C=
	 *            所在国家
	 * @param keyName
	 *            数字证书的别名默认mykey
	 * @return object[0]=P10格式数据 object[1]=数字证书keystore object[2]=数字证书密码
	 * @throws Exception
	 *             生成证书失败
	 */
	public static Object[] getCfcaP10_3(String certDn, String keyName) throws Exception {
		Object[] obj = new Object[3];
		// 产生8位随机密码
		String passwrod = StringUtil.getRandomString(8);
		X509Certificate cert = null;
		ByteArrayOutputStream keystoreFile = null;
		String signAlgorithm = "SHA1WithRSA"; // 设置证书的加密方式
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
		store.load(null, null);
		kpg = KeyPairGenerator.getInstance("RSA");// 设置证书的加密方式
		//cfca需要2048长度的秘钥
		kpg.initialize(2048);
		KeyPair keyPair = kpg.generateKeyPair();
		PublicKey pubKey = keyPair.getPublic();
		// 私钥
		PrivateKey priKey = keyPair.getPrivate();
		X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
		X500Principal xp = new X500Principal(certDn);
//		System.out.println("证书标题：" + certDn + "---" + keyName);
		certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
		// 设置颁发者
		certGen.setIssuerDN(xp);
		// 设置使用者
		// 设置有效期
		certGen.setNotBefore(new Date());

		Calendar calendar = Calendar.getInstance();
		Date date = new Date(System.currentTimeMillis());
		calendar.setTime(date);
		calendar.add(Calendar.DATE, +1);
		certGen.setNotAfter(calendar.getTime());

		certGen.setSubjectDN(xp);
		// 公钥
		certGen.setPublicKey(pubKey);
		certGen.setSignatureAlgorithm(signAlgorithm);
		cert = certGen.generateX509Certificate(keyPair.getPrivate(), "BC");
		// 将证书信息写入到jks中
		store.setKeyEntry(keyName, keyPair.getPrivate(), passwrod.toCharArray(), new Certificate[] { cert });
		PKCS10CertificationRequest p10CertificationRequest = new PKCS10CertificationRequest(signAlgorithm, xp,
				keyPair.getPublic(), null, keyPair.getPrivate());
		// 得到p10格式数据
		String p10 = new String(Base64.encode(p10CertificationRequest.getEncoded()));
		keystoreFile = new ByteArrayOutputStream();
		store.store(keystoreFile, passwrod.toCharArray()); // 获取生成数字证书
		obj[0] = p10;
		obj[1] = keystoreFile.toByteArray();
		obj[2] = passwrod;
		if (keystoreFile != null)
			keystoreFile.close();
		return obj;

	}

	/**
	 * 
	 * 生成keystore和P10。。
	 * 
	 * @param certDn
	 *            certDn证书的标题如：CN=某某,OU=身份证号或企业证件号,O=哪家公司帮某某申请,L=省份,ST=企业城市,C=
	 *            所在国家
	 * @param keyName
	 *            数字证书的别名默认mykey
	 * @return object[0]=P10格式数据 object[1]=数字证书keystore object[2]=数字证书密码
	 * @throws Exception
	 *             生成证书失败
	 */
	public static Object[] getZQP10_3(String certDn, String keyName) throws Exception {
		Object[] obj = new Object[4];
		// 产生8位随机密码
		String passwrod = StringUtil.getRandomString(8);
		X509Certificate cert = null;
		ByteArrayOutputStream keystoreFile = null;
		String signAlgorithm = "SHA1WithRSA"; // 设置证书的加密方式
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
		store.load(null, null);
		kpg = KeyPairGenerator.getInstance("RSA");// 设置证书的加密方式
		//cfca需要2048长度的秘钥
		kpg.initialize(2048);
		KeyPair keyPair = kpg.generateKeyPair();
		PublicKey pubKey = keyPair.getPublic();
		// 私钥
		PrivateKey priKey = keyPair.getPrivate();
		X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
		X500Principal xp = new X500Principal(certDn);
//		System.out.println("证书标题：" + certDn + "---" + keyName);
		certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
		// 设置颁发者
		certGen.setIssuerDN(xp);
		// 设置使用者
		// 设置有效期
		certGen.setNotBefore(new Date());

		Calendar calendar = Calendar.getInstance();
		Date date = new Date(System.currentTimeMillis());
		calendar.setTime(date);
		calendar.add(Calendar.YEAR, +1);
		certGen.setNotAfter(calendar.getTime());

		certGen.setSubjectDN(xp);
		// 公钥
		certGen.setPublicKey(pubKey);
		certGen.setSignatureAlgorithm(signAlgorithm);
		cert = certGen.generateX509Certificate(keyPair.getPrivate(), "BC");
		// 将证书信息写入到jks中
		store.setKeyEntry(keyName, keyPair.getPrivate(), passwrod.toCharArray(), new Certificate[] { cert });
		PKCS10CertificationRequest p10CertificationRequest = new PKCS10CertificationRequest(signAlgorithm, xp,
				keyPair.getPublic(), null, keyPair.getPrivate());
		// 得到p10格式数据
		String p10 = new String(Base64.encode(p10CertificationRequest.getEncoded()));
		keystoreFile = new ByteArrayOutputStream();
		store.store(keystoreFile, passwrod.toCharArray()); // 获取生成数字证书
		obj[0] = p10;
		obj[1] = keystoreFile.toByteArray();
		obj[2] = passwrod;
		//获取个人证书数据
		byte[] encoded = cert.getEncoded();
		obj[3] = encoded ;
		
		if (keystoreFile != null)
			keystoreFile.close();
		return obj;

	}
	public static String getP7B(byte[] zqCert, byte[] p10, String pwd) throws Exception {

		char[] storepass = pwd.toCharArray();
		char[] cakeypass = pwd.toCharArray();
		String alias = "my";
		String name = "my";

		// Cert of CA从密钥库读取CA的证书
		// 这里的name的值为“mykeystore”,alias的值为“mytest”
		ByteArrayInputStream fis = new ByteArrayInputStream(zqCert);
		KeyStore ks = KeyStore.getInstance("PKCS12","BC");
		ks.load(fis, storepass);
		java.security.cert.Certificate cl = ks.getCertificate(alias);

		// 从密钥库读取CA的私钥
		// 执行KeyStore对象的getKey()方法，获取其参数对应的条目的私钥，保护私钥的口令也通过方法的参数传入
		PrivateKey caprk = (PrivateKey) ks.getKey(alias, cakeypass);
		fis.close();

		
		
//		CertificateFactory zqC = CertificateFactory.getInstance("X.509");
//		ByteArrayInputStream zq = new ByteArrayInputStream(zqCert);
//		java.security.cert.Certificate cl = zqC.generateCertificate(zq);
		
		
		// 从CA的证书中提取签发者的信息
		// 首先提取CA证书的编码，然后用该编码创建X509CerImpl类型的对象
		byte[] encoal = cl.getEncoded();
		
		X509CertImpl cimpl = new X509CertImpl(encoal);
		// 通过该对象的get()方法获取X509CerInfo类型的对象，该对象封装的全部内容
		X509CertInfo cinfol = (X509CertInfo) cimpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);
		// 最后通过该对象的get()方法获得X509Name类型的签发者信息
		X500Name issuer = (X500Name) cinfol.get(X509CertInfo.SUBJECT + "." + CertificateIssuerName.DN_NAME);

		// 获取待签发的证书
		CertificateFactory of = CertificateFactory.getInstance("X.509");
		ByteArrayInputStream userP10 = new ByteArrayInputStream(p10);
		java.security.cert.Certificate c2 = of.generateCertificate(userP10);

		// 从待签发的数字证书提取证书的信息
		// 先提取待签发者的证书编码，然后创建X509CertImpl类型的对象，最后通过该对象的get()方法获取X509CertInfo类型的对象，以后就可以使用该对象创建新的证书了
		byte[] encod2 = c2.getEncoded();
		X509CertImpl cimp2 = new X509CertImpl(encod2);
		X509CertInfo cinfo2 = (X509CertInfo) cimp2.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

		// 设置新证书有效期
		// 新证书的开始生效时间是从签发之时开始，因此首先使用new Date()获取但是时间。
		// 证书有效时间为15分钟
		// 同过两个日期创建CertificateValidity类型的对象，并且把它作为参数传递给上一步得到X509CertInfo对象的set()方法已设置有效期
		Date begindate = new Date();
		Date enddate = new Date(begindate.getTime() + 365 * 24 * 60 * 60 * 1000L);
		CertificateValidity cv = new CertificateValidity(begindate, enddate);

		cinfo2.set(X509CertInfo.VALIDITY, cv);

		// 设置新证书序列号。每个证书都有唯一的一个序列号。这里以当前时间（以秒为单位）为序列号，创建CertificateSerialNumber对象，并作为参数传递给X509CertInfo对象的set()方法以设置序列号
		int sn = (int) (begindate.getTime() / 1000);
		CertificateSerialNumber csn = new CertificateSerialNumber(sn);
		cinfo2.set(X509CertInfo.SERIAL_NUMBER, csn);

		// 设置新证书的签发者。执行X509CertInfo对象的set()方法设置签发者，传入参数即从CA的证书中提取的签发者信息
		cinfo2.set(X509CertInfo.ISSUER + "." + CertificateIssuerName.DN_NAME, issuer);

		// 设置新证书的签名算法信息
		// 首先生成AlgorithmId类型的对象，在其构造器中指定CA签名该证书所使用的算法为md5WithRSA，然后将其作为参数传递给X509CertInfo对象的set()方法以设置签名算法信息
		AlgorithmId alogorithm = new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid);
		cinfo2.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, alogorithm);
		// cinfo2.set(CertificateAlgorithmId.NAME + "." +
		// CertificateAlgorithmId.ALGORITHM, algoritbm);

		// 创建证书并使用CA的私钥对其签名
		// X509CertImpl是X509证书的底层实现，将待签发的证书信息传递给其构造器，将得到新的证书，执行其sign()方法，将使用CA
		X509CertImpl newcert = new X509CertImpl(cinfo2);
		newcert.sign(caprk, "SHA1WithRSA");
//		newcert.sign(caprk, "MDSWithRSA");

		// 将新的证书存入密钥库
//		ks.setCertificateEntry("if_signed", newcert);
		/*
		 * snivateKey prk=(Frivatekey)ks.getkey("Lf","wishnout".toCharArray);
		 * java.security.cert.Certificate[] conai=(new cert);
		 * ks.setKeyEntry("if_signed,prk","newpass",oCharArray(),conain);
		 */
		byte[] signature = newcert.getEncoded();
//		FileOutputStream out = new FileOutputStream("newstore");
//		ks.store(out, "newpass".toCharArray());
//		out.close();
		return Base64.encode(signature);
	}
	/**
	 * 将base64转成字节数组。
	 * 
	 * @param base64
	 *            需要转化的base64字符串
	 * @return flie base64对应的字节数字
	 */
	/*
	 * public byte[] baseToByte(String base64) { byte [] flie = null;
	 * ByteArrayOutputStream outputStream = null; try { // 解码，然后将字节转换为文件
	 * 
	 * byte[] bytes ;//= Base64.decode(base64, Base64.DEFAULT);// 将字符串转换为byte数组
	 * sun.misc.BASE64Decoder decode = new sun.misc.BASE64Decoder(); try { bytes
	 * = decode.decodeBuffer(base64); } catch (IOException e1) { throw new
	 * RuntimeException("文件转化失败"); }
	 * 
	 * ByteArrayInputStream in = new ByteArrayInputStream(bytes); byte[] buffer
	 * = new byte[1024]; outputStream = new ByteArrayOutputStream(); int bytesum
	 * = 0; int byteread = 0; while ((byteread = in.read(buffer)) != -1) {
	 * bytesum += byteread; outputStream.write(buffer, 0, byteread); // 文件写操作 }
	 * flie = outputStream.toByteArray(); } catch (IOException ioe) {
	 * ioe.printStackTrace(); } finally { try {
	 * if(outputStream!=null)outputStream.close(); } catch (IOException e) {
	 * e.printStackTrace(); } } return flie; }
	 */
	/**
	 * 
	 * CFCA证书导入到keystore中。
	 * 
	 * @param p7bFile
	 *            CA颁发数字证书
	 * @param jksFile
	 *            证书文件keystore
	 * @param name
	 *            证书别名
	 * @param password
	 *            证书密码
	 * @return file 带有CA颁发的数字证书
	 * @throws Exception
	 *             导入异常
	 * @throws NullPointerException
	 *             无
	 */
	@SuppressWarnings("unchecked")
	public static byte[] certZQWriteInJks(byte[] p7bFile, byte[] jksFile, String name, String password) throws Exception {

		// 加载jks文件
		InputStream in = new ByteArrayInputStream(jksFile);
		// ByteOutputStream byteOutputStream = new ByteOutputStream();
		KeyStore ks = KeyStore.getInstance("JKS");// 设置类型
		ks.load(in, password.toCharArray());
		// 获取别名为name的私钥
		PrivateKeyEntry key = (PrivateKeyEntry) ks.getEntry(name, new PasswordProtection(password.toCharArray()));
		InputStream caFis = new ByteArrayInputStream(p7bFile);// 加载ca发放证书
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		List<Certificate> cert = (List<Certificate>) cf.generateCertificates(caFis);// 获取ca颁发的证书
		ByteArrayOutputStream keystoreFile = null;
		byte[] file = null;
		try {
			// 生成一个新的keystore
			KeyStore store = KeyStore.getInstance("JKS");
			store.load(null, null);
			// 将ca证书写入本地密钥库的私钥
			store.setKeyEntry(name, key.getPrivateKey(), password.toCharArray(), new Certificate[] { cert.get(0) });
			keystoreFile = new ByteArrayOutputStream();
			store.store(keystoreFile, password.toCharArray());
			file = keystoreFile.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (keystoreFile != null) {
				keystoreFile.close();
			}
			if (in != null) {
				in.close();
			}
			if (caFis != null) {
				caFis.close();
			}
		}
		return file;
	}
	/**
	 * 
	 * CFCA证书导入到keystore中。
	 * 
	 * @param p7bFile
	 *            CA颁发数字证书
	 * @param jksFile
	 *            证书文件keystore
	 * @param name
	 *            证书别名
	 * @param password
	 *            证书密码
	 * @return file 带有CA颁发的数字证书
	 * @throws Exception
	 *             导入异常
	 * @throws NullPointerException
	 *             无
	 */
	@SuppressWarnings("unchecked")
	public static byte[] certCfcaWriteInJks(byte[] p7bFile, byte[] jksFile, String name, String password) throws Exception {

		// 加载jks文件
		InputStream in = new ByteArrayInputStream(jksFile);
		// ByteOutputStream byteOutputStream = new ByteOutputStream();
		KeyStore ks = KeyStore.getInstance("JKS");// 设置类型
		ks.load(in, password.toCharArray());
		// 获取别名为name的私钥
		PrivateKeyEntry key = (PrivateKeyEntry) ks.getEntry(name, new PasswordProtection(password.toCharArray()));
		InputStream caFis = new ByteArrayInputStream(p7bFile);// 加载ca发放证书
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		List<Certificate> cert = (List<Certificate>) cf.generateCertificates(caFis);// 获取ca颁发的证书
		ByteArrayOutputStream keystoreFile = null;
		byte[] file = null;
		try {
			// 生成一个新的keystore
			KeyStore store = KeyStore.getInstance("JKS");
			store.load(null, null);
			// 将ca证书写入本地密钥库的私钥
			store.setKeyEntry(name, key.getPrivateKey(), password.toCharArray(), new Certificate[] { cert.get(0) });
			keystoreFile = new ByteArrayOutputStream();
			store.store(keystoreFile, password.toCharArray());
			file = keystoreFile.toByteArray();
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			if (keystoreFile != null) {
				keystoreFile.close();
			}
			if (in != null) {
				in.close();
			}
			if (caFis != null) {
				caFis.close();
			}
		}
		return file;
	}
	/**
	 * 
	 * CA证书导入到keystore中。
	 * 
	 * @param p7bFile
	 *            CA颁发数字证书
	 * @param jksFile
	 *            证书文件keystore
	 * @param name
	 *            证书别名
	 * @param password
	 *            证书密码
	 * @return file 带有CA颁发的数字证书
	 * @throws Exception
	 *             导入异常
	 * @throws NullPointerException
	 *             无
	 */
	@SuppressWarnings("unchecked")
	public static byte[] certCAWriteInJks(byte[] p7bFile, byte[] jksFile, String name, String password) throws Exception {

		// 加载jks文件
		InputStream in = new ByteArrayInputStream(jksFile);
		// ByteOutputStream byteOutputStream = new ByteOutputStream();
		KeyStore ks = KeyStore.getInstance("JKS");// 设置类型
		ks.load(in, password.toCharArray());
		// 获取别名为name的私钥
		PrivateKeyEntry key = (PrivateKeyEntry) ks.getEntry(name, new PasswordProtection(password.toCharArray()));
		InputStream caFis = new ByteArrayInputStream(p7bFile);// 加载ca发放证书
		CertificateFactory cf = CertificateFactory.getInstance("X.509");
		List<Certificate> cert = (List<Certificate>) cf.generateCertificates(caFis);// 获取ca颁发的证书
		ByteArrayOutputStream keystoreFile = null;
		byte[] file = null;
		try {
			// 生成一个新的keystore
			KeyStore store = KeyStore.getInstance("JKS");
			store.load(null, null);
			// 将ca证书写入本地密钥库的私钥
			store.setKeyEntry(name, key.getPrivateKey(), password.toCharArray(), new Certificate[] { cert.get(1) });
			keystoreFile = new ByteArrayOutputStream();
			store.store(keystoreFile, password.toCharArray());
			file = keystoreFile.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (keystoreFile != null) {
				keystoreFile.close();
			}
			if (in != null) {
				in.close();
			}
			if (caFis != null) {
				caFis.close();
			}
		}
		return file;
	}

	/**
	 * 
	 * JKS导出证书。
	 * 
	 * @param password
	 *            证书密码
	 * @param allJksFile
	 *            证书文件
	 * @return pfx证书
	 * @throws IOException
	 *             文件装换失败
	 * @throws NullPointerException
	 *             说明发生此异常的条件
	 */
	public static byte[] covertJSKToPFX(String password, byte[] allJksFile) throws IOException {
		ByteArrayInputStream fis = null;
		ByteArrayOutputStream keystoreFile = null;
		OutputStream out = null;
		byte[] file = null;
		try {
			// 设置KeyStore类型
			KeyStore inputKeyStore = KeyStore.getInstance("JKS");
			fis = new ByteArrayInputStream(allJksFile);
			char[] srcPwd = password == null ? null : password.toCharArray();
			char[] destPwd = password == null ? null : password.toCharArray();
			// 加载数字证书
			inputKeyStore.load(fis, srcPwd);
			// 设置需要导出的数字证书类型
			KeyStore outputKeyStore = KeyStore.getInstance("PKCS12");
			// 获取数字证书里面所有证书链别名 一般只有一个
			Enumeration enums = inputKeyStore.aliases();
			// 遍历 取出证书里别enums里的别名证书
			while (enums.hasMoreElements()) {
				String keyAlias = (String) enums.nextElement();
				outputKeyStore.load(null, destPwd);
				if (inputKeyStore.isKeyEntry(keyAlias)) {
					Key key = inputKeyStore.getKey(keyAlias, srcPwd);
					java.security.cert.Certificate[] certChain = inputKeyStore.getCertificateChain(keyAlias);
					outputKeyStore.setKeyEntry(keyAlias, key, destPwd, certChain);
				}
				keystoreFile = new ByteArrayOutputStream();
				// out = new FileOutputStream(new File("d:/test/zq.pfx"));
				outputKeyStore.store(keystoreFile, destPwd);
				outputKeyStore.deleteEntry(keyAlias);
				file = keystoreFile.toByteArray();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (keystoreFile != null) {
				keystoreFile.close();
			}
			if (out != null) {
				out.close();
			}
		}
		return file;
	}

	public static void main(String[] args) throws Exception {
		CertificateDealt certificateDealt = new CertificateDealt();
		certificateDealt.getP10_3("CN=王文婷,OU=6124011991031841751@1486691746747,O=北京众签科技有限公司,L=北京,ST=北京,C=CN", "my");
	}
}
